package com.example.task1.test;


import com.example.task1.application.MyApplication;
import com.example.task1.util.ApiResp;
import com.example.task1.util.CallBack;
import com.google.gson.Gson;

import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.http.Body;
import retrofit2.http.DELETE;
import retrofit2.http.GET;
import retrofit2.http.Header;
import retrofit2.http.POST;
import retrofit2.http.PUT;
import retrofit2.http.Url;

public class ApiClient {
    private static Retrofit retrofit;

    private static Gson sGson = new Gson();

    public static IApiService getApi(Class bean) {
       return new Retrofit.Builder()
                .baseUrl(MyApplication.BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build().create(IApiService.class);
    }

    public static void send(Call<ApiResp> call, Class bean, CallBack back){
        call.enqueue(new Callback<ApiResp>() {
            @Override
            public void onResponse(Call<ApiResp> call, Response<ApiResp> response) {
                ApiResp body = response.body();
                if (body.getCode() == 200) {
                    back.success(sGson.fromJson(sGson.toJson(body),bean));
                }else {
                    back.error(body.getMsg());
                }
            }

            @Override
            public void onFailure(Call<ApiResp> call, Throwable throwable) {
            }
        });
    }

    public interface IApiService {

        @POST
        Call<ApiResp> post(@Header("Authorization") String token, @Url String url, @Body RequestBody requestBody);

        @GET
        Call<ApiResp> get(@Url String url);

        @PUT
        Call<ApiResp> put(@Header("Authorization") String token, @Url String url, @Body RequestBody requestBody);

        @DELETE
        Call<ApiResp> delete(@Header("Authorization") String token, @Url String url, @Body RequestBody requestBody);

    }

}
